﻿
using LuxsanBaseHelpLib;
using LuxsanCommunicationTool.Communication.TcpIp;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;


namespace LuxsanTool.Tool
{
    public class Other1BaseTool : BaseTool
    {
        public Other1BaseTool(string _strToolName)
        {
            this.m_strToolName = _strToolName;
            this.m_EditId = (int)ToolEnum.ToolEditEnum.脚本编辑工具;
            this.m_bEnable = false;
            this.m_bLogEnable = false;
            m_UserControl_Other1Tool = new UserControl_Other1Tool(this);
        }

        /// <summary>
        /// 脚本编译器进入点
        /// </summary>
        public Other1BaseTool()
        {
        }

        public void  SetOther1BaseTool(string _strToolName)
        {
            this.m_strToolName = _strToolName;
            this.m_EditId = (int)ToolEnum.ToolEditEnum.脚本编辑工具;
            this.m_bEnable = false;
            this.m_bLogEnable = false;
            m_UserControl_Other1Tool = new UserControl_Other1Tool(this);
        }

        public UserControl_Other1Tool m_UserControl_Other1Tool;


        //Other1Result m_AtlasResult = new Other1Result();

        /// <summary>
        /// 通讯名称
        /// </summary>
        public string m_strCommunicationName;
        /// <summary>
        /// 通讯类型
        /// </summary>
        public int m_iCommunicationType;

        /// <summary>
        /// 类库名称
        /// </summary>
        string m_strLibName;


        int itimeout;


        /// <summary>脚本构造器</summary>
        //public  WagScriptBuild<Other1Tool> m_Scriptbuild = null;

        
        /// <summary>
        /// 读取到的值
        /// </summary>
        public byte[] byteReadValue = new byte[0];
        /// <summary>
        /// 读取到的值
        /// </summary>
        public string strReadValue = "";

        //public string strScriptCode = "";

        #region  Initial 初始化
        /// <summary>
        /// 初始化
        /// </summary>
        public override void Initial()
        {
            m_strLibName = typeof(Other1BaseTool).Name;

            LoadToolInPutValue();
            LoadReadValueToolConfig();
            m_UserControl_Other1Tool.SetParaToForm();
            m_UserControl_Other1Tool.InPutValueParaToForm();

            try
            {
                AssistToolOutPutValue(); 
                m_UserControl_Other1Tool.OutPutValueParaToForm();
            }
            catch (Exception ex)
            {

            }
          
            DisRunResult();

            //注册脚本编辑器
            //IntialSriptEditor();
        }
        #endregion

        #region RegSriptEditor 注册脚本编辑器
        /// <summary>
        /// 注册脚本编辑器
        /// </summary>
        //public void IntialSriptEditor()
        //{
        //    //软件启动的地方加上脚本组件的注册（演示版授权）
        //    string regMessage = "";
        //    bool regSuccess  = WagScriptLic.Reg("community", "a33f0a5e03b6c4de9144e56ec138c21ab016298368f5e86e776fddd19fcc43fe3567a626401b6df109870433322c232301cc57472c769ad142b957c346917cf5b080b940acb7db8dc838915e676685a31306581e0d7c87f9187dec63010e8dc6c1a361531de700a367053e60746dadc45b3d4d6a7572948ad499064ba0592fc70e9007bef9c83ada035d91d7f237dfbd7ea7d8661a65739a074680470a33a114c1c0a4950774f785ecfc35aa53783333beacf9904f089326f4e217b72cc7805d3bfec6188660864367a583d48d466bdaa667d2d9aee5d13414cf493409b230cd72a1b4e99b2d62e0117e9198645d6833ad3969c428fffe1075b5ef12dd4244eced9b5ae7d6aed9480a543e8d175879ffb4b63530c2aa14dad7f67c2c29daddd9800d43856d3623ced49fdd9f1e5855a5", ref regMessage);
        //    if (!regSuccess)
        //    {
        //        MessageBox.Show(regMessage, "注册脚本编辑");
        //    }

        //    if (!string.IsNullOrWhiteSpace(strScriptCode))
        //    {
        //        m_Scriptbuild = new WagScriptBuild<Other1Tool>(strScriptCode);
        //        Other1Tool m_other1Tool = m_Scriptbuild.BuildScript(false);//编译脚本
        //        if (m_other1Tool == null)
        //        {
        //            m_executeStatus.bStatus = false;
        //            m_executeStatus.strErrorMsg = $"脚本编译异常: {m_Scriptbuild.m_sScriptError}";
        //            DisRunResult();
        //        }
        //    }
            //m_UserControl_Other1Tool.AddScriptControl();
        //}
        #endregion

        #region  Realse 释放资源
        /// <summary>
        /// 释放资源 
        /// </summary>
        public override void Realse()
        {
        }
        #endregion

        #region SavePara 保存参数
        /// <summary>
        /// 保存参数
        /// </summary>
        public override void SavePara()
        {
            m_UserControl_Other1Tool.FormToSetPara();
            SaveComReadValueToolConfig();
            SaveToolInPutValue();
        }
        #endregion

        #region  SetSize 设定控件尺寸大小
        public override void SetSize(int Width, int Height)
        {
            m_UserControl_Other1Tool.SetSize(Width, Height);
        }
        #endregion

        #region   ModifiedDisToForm 调整后所有参数显示到界面
        /// <summary>
        /// 调整后所有参数显示到界面
        /// </summary>
        public override void ModifiedDisToForm()
        {
            m_UserControl_Other1Tool.FormToSetPara();
            m_UserControl_Other1Tool.SetParaToForm();
          
            m_UserControl_Other1Tool.OutPutValueParaToForm();
        }
        #endregion

        #region  DisRunResult 
        /// <summary>
        /// 显示运行结果
        /// </summary>
        public override void DisRunResult()
        {
            m_UserControl_Other1Tool.DisRunResult();
        }
        #endregion



        #region ModifyComConfig  调整引用通讯名 (调整通讯名的时候调用)
        /// <summary>
        ///  调整引用通讯名 (调整通讯名的时候调用)

        /// </summary>
        /// <param name="_strNewStationName"></param>
        /// <param name="_strOldStationName"></param>
        public override void ModifyComConfigName(string _strNewComName, string _strOldComName)
        {

            Type type = typeof(Other1BaseTool);
            MemberInfo[] memberInfo = type.GetMember("m_strCommunicationName");
            int iCount = memberInfo.Count();
            if (iCount > 0)
            {
                if (this.m_strCommunicationName == _strOldComName)
                {
                    this.m_strCommunicationName = _strNewComName;
                }
            }
        }
        #endregion

        #region DeleteComConfig删除引用通讯名 (调整通讯名的时候调用)
        /// <summary>
        /// 删除引用通讯名 (调整通讯名的时候调用)
        /// </summary>
        /// <param name="_strNewStationName"></param>
        /// <param name="_strOldStationName"></param>
        public override void DeleteComConfigName(string _strDeleteToolName)
        {
            Type type = typeof(ComReadValueTool);
            MemberInfo[] memberInfo = type.GetMember("m_strCommunicationName");
            int iCount = memberInfo.Count();
            if (iCount > 0)
            {
                if (this.m_strCommunicationName == _strDeleteToolName)
                {
                    this.m_strCommunicationName = "";
                    this.m_iCommunicationType = 0;
                }
            }
        }
        #endregion

     


        #region  SaveComReadValueToolConfig  保存通讯配置
        /// <summary>
        /// 保存通讯配置
        /// </summary>
        public void SaveComReadValueToolConfig()
        {
            string strFilePath = m_strFilePath + "\\" + m_strStationName;
            //判断文件是否存在
            if (!(System.IO.Directory.Exists(strFilePath)))
                System.IO.Directory.CreateDirectory(strFilePath);

            //if (System.IO.File.Exists(strFilePath + "\\AtlasTool.ini"))
            //    System.IO.File.Delete(strFilePath + "\\AtlasTool.ini");

            if (m_iToolDelayTimeFront > 1000)
                m_iToolDelayTimeFront = 1000;
            if (m_iToolDelayTimeBack > 1000)
                m_iToolDelayTimeBack = 1000;

            m_iniFile.WtiteString(this.m_strToolName + "Item", "Enable", m_bEnable.ToString(), strFilePath + "\\Other1Tool.ini");
            m_iniFile.WtiteString(this.m_strToolName + "Item", "LogEnable", m_bLogEnable.ToString(), strFilePath + "\\Other1Tool.ini");

            m_iniFile.WtiteString(this.m_strToolName + "Item", "ToolDelayTimeFront", m_iToolDelayTimeFront.ToString(), strFilePath + "\\Other1Tool.ini");
            m_iniFile.WtiteString(this.m_strToolName + "Item", "ToolDelayTimeBack", m_iToolDelayTimeBack.ToString(), strFilePath + "\\Other1Tool.ini");



            m_iniFile.WtiteString(this.m_strToolName + "Item", "strCommunicationName", m_strCommunicationName, strFilePath + "\\Other1Tool.ini");
            m_iniFile.WtiteString(this.m_strToolName + "Item", "iCommunicationType", m_iCommunicationType.ToString(), strFilePath + "\\Other1Tool.ini");

            //m_Scriptbuild.BuildScript(true);
            //m_Scriptbuild = new WagScriptBuild<Other1Tool>(strScriptCode);
            //string strCode = m_Scriptbuild.m_WagScriptSupport.SaveToStr("");
            //strScriptCode = strCode;

            //File.WriteAllText(strFilePath + "\\" + this.m_strToolName + ".script", strScriptCode, Encoding.UTF8);

            //存储修改后的脚本到文件
            //Other1Tool m_other1Tool = m_Scriptbuild.BuildScript(false);//编译脚本
            //if(m_other1Tool==null)
            //MessageBox.Show("脚本工具编译失败", "编译脚本");

        }
        #endregion

        #region LoadReadValueToolConfig  保存通讯配置
        /// <summary>
        /// 保存通讯配置
        /// </summary>
        public void LoadReadValueToolConfig()
        {
            string strFilePath = m_strFilePath + "\\" + m_strStationName;

            //判断文件是否存在
            if (!(System.IO.Directory.Exists(strFilePath)))
                System.IO.Directory.CreateDirectory(strFilePath);

            string strEnable = m_iniFile.GetString(this.m_strToolName + "Item", "Enable", strFilePath + "\\Other1Tool.ini");
            bool.TryParse(strEnable, out m_bEnable);
            string strLogEnable = m_iniFile.GetString(this.m_strToolName + "Item", "LogEnable", strFilePath + "\\Other1Tool.ini");
            bool.TryParse(strLogEnable, out m_bLogEnable);

            m_iToolDelayTimeFront = m_iniFile.GetInt(this.m_strToolName + "Item", "ToolDelayTimeFront", strFilePath + "\\Other1Tool.ini");
            m_iToolDelayTimeBack = m_iniFile.GetInt(this.m_strToolName + "Item", "ToolDelayTimeBack", strFilePath + "\\Other1Tool.ini");

            m_strCommunicationName = m_iniFile.GetString(this.m_strToolName + "Item", "strCommunicationName", strFilePath + "\\Other1Tool.ini");
            m_iCommunicationType = m_iniFile.GetInt(this.m_strToolName + "Item", "iCommunicationType", strFilePath + "\\Other1Tool.ini");

            //读取脚本
            //if (!File.Exists(strFilePath + "\\" + this.m_strToolName + ".script"))
            //{
            //    if (!File.Exists(Application.StartupPath+ "\\template.script"))
            //    {
            //        MessageBox.Show(Application.StartupPath + "\\template.script"+" 未加载到模板脚本", "注册脚本编辑");
            //        return;
            //    }
            //    File.Copy(Application.StartupPath+"\\template.script", strFilePath + "\\" + this.m_strToolName + ".script");
            //}

            //strScriptCode =File.ReadAllText(strFilePath + "\\" + this.m_strToolName + ".script", Encoding.UTF8);
           
        }
        #endregion


        #region AddInputValue 添加输入值
        /// <summary>
        /// 添加输入值
        /// </summary>
        /// <param name="_variable"></param>
        /// <returns></returns>
        public LuxsanBaseHelpLib.ExecuteStatus AddInputValue(ToolInputValue _toolInputValue)
        {
            LuxsanBaseHelpLib.ExecuteStatus executeStatus = new LuxsanBaseHelpLib.ExecuteStatus();


            List<string> listKey = m_ToolInputValue.Keys.ToList();
            if (!listKey.Contains(_toolInputValue.strName))
            {
                m_ToolInputValue.Add(_toolInputValue.strName, _toolInputValue);
                executeStatus.bStatus = true;
                executeStatus.strErrorMsg = "";
            }
            else
            {
                executeStatus.bStatus = false;
                executeStatus.strErrorMsg = "ToolInputValue is Existed";
            }
            return executeStatus;
        }
        #endregion

        #region  ModifyInputValue 调整输入值
        /// <summary>
        /// 调整输入值
        /// </summary>
        /// <param name="_strStationNmae"></param>
        /// <param name="_StationWork"></param>
        /// <returns></returns>
        public LuxsanBaseHelpLib.ExecuteStatus ModifyInputValue(string _strModifyName, ToolInputValue _toolInputValue)
        {
            LuxsanBaseHelpLib.ExecuteStatus executeStatus = new LuxsanBaseHelpLib.ExecuteStatus();

            if (m_ToolInputValue.Keys.Contains(_strModifyName))
            {
                if (_strModifyName == _toolInputValue.strName)
                {
                    m_ToolInputValue[_strModifyName] = _toolInputValue;
                    executeStatus.bStatus = true;
                    executeStatus.strErrorMsg = "";
                }
                else
                {
                    //m_ToolInputValue.Remove(_strModifyName);
                    executeStatus = AddInputValue(_toolInputValue);
                    if (executeStatus.bStatus)
                        m_ToolInputValue.Remove(_strModifyName);
                }
            }
            else
            {
                executeStatus.bStatus = false;
                executeStatus.strErrorMsg = "ToolInputValue is No Existed ";
            }

            return executeStatus;
        }
        #endregion

        #region DeleteInputValue 删除输入值
        /// <summary>
        /// 删除输入值
        /// </summary>
        /// <param name="_strName"></param>
        /// <returns></returns>
        public LuxsanBaseHelpLib.ExecuteStatus DeleteInputValue(string _strName)
        {
            LuxsanBaseHelpLib.ExecuteStatus executeStatus = new LuxsanBaseHelpLib.ExecuteStatus();
            if (m_ToolInputValue.Keys.Contains(_strName))
            {

                m_ToolInputValue.Remove(_strName);
                executeStatus.bStatus = true;
                executeStatus.strErrorMsg = "";
            }
            else
            {
                executeStatus.bStatus = false;
                executeStatus.strErrorMsg = "ToolInputValue is  No Existed ";
            }
            return executeStatus;
        }
        #endregion

        #region SetToolOutPutValue 分配输出值
        /// <summary>
        /// 分配输出值
        /// </summary>
        public void SetToolOutPutValue(string _strName, object _object)
        {
            ToolOutPutValue toolOutPutValue = new ToolOutPutValue();
            toolOutPutValue.strName = _strName;
            if (_object != null)
            {
                toolOutPutValue.strType = _object.GetType().Name;
            }
            toolOutPutValue.objValue = _object;

            if (!m_ToolOutPutValue.ContainsKey(_strName))
                m_ToolOutPutValue.Add(toolOutPutValue.strName, toolOutPutValue);
        }
        #endregion

        #region  AssistToolOutPutValue 分配输出
        /// <summary>
        /// AssistToolOutPutValue 分配输出
        /// </summary>
        /// <returns></returns>
        public override void AssistToolOutPutValue()
        {
            m_ToolOutPutValue.Clear();
           
                SetToolOutPutValue("工具运行时间(ms)", m_stopwatchStart.ElapsedMilliseconds.ToString());
                SetToolOutPutValue("工具名称", this.m_strToolName);

                SetToolOutPutValue("运行结果", m_executeStatus.bStatus);
                SetToolOutPutValue("运行信息", m_executeStatus.strErrorMsg);
           
        }
        #endregion

        #region RunTool  运行工具
        /// <summary>
        /// 运行工具
        /// </summary>
        public override LuxsanBaseHelpLib.ExecuteStatus RunTool()
        {
            string strRunMsg = "";
            m_stopwatchStart.Restart();

           
            try
            {
                Thread.Sleep(m_iToolDelayTimeFront);

              
            }
            catch (Exception ex)
            {
                m_executeStatus.bStatus = false;
                m_executeStatus.strErrorMsg = "【" + this.m_strToolName + "】" + ex.Message;
                SaveLog(m_executeStatus.strErrorMsg, _bDisForm: true);
            }

            Thread.Sleep(m_iToolDelayTimeBack);
            m_stopwatchStart.Stop();
          
            try
            {
                AssistToolOutPutValue();
                m_UserControl_Other1Tool.OutPutValueParaToForm();
            }
            catch (Exception ex)
            {
                strRunMsg = "【" + this.m_strToolName + "】输出值分配异常 " + ex.Message;
                SaveLog(strRunMsg, _bDisForm: true);
            }

            return m_executeStatus;
        }
        #endregion

        #region SaveLog   保存LOG
        /// <summary>
        /// 保存LOG
        /// </summary>
        /// <param name="_strLogMag"></param>
        /// <param name="_bSaveAlarm"></param>
        /// <param name="_bSaveOtherMark"></param>
        public override void SaveLog(string _strLogMag, bool _bSaveAlarm = true, bool _bSaveOtherMark = true, bool _bDisForm = false)
        {

            if (m_LuxsanToolDelegate == null)
                return;
            if (this.m_bLogEnable && !m_executeStatus.bStatus && _bSaveAlarm)
                m_LuxsanToolDelegate("ExceptionLog", this.m_strLogName, m_strStationName, _strLogMag, _bDisForm);

            if (this.m_bLogEnable)
                m_LuxsanToolDelegate("RunningLog", this.m_strLogName, m_strStationName, _strLogMag, _bDisForm);


            if (this.m_bLogEnable && _bSaveOtherMark)
                m_LuxsanToolDelegate("PDCALog", this.m_strLogName, m_strStationName, _strLogMag, _bDisForm);

        }
        #endregion


    }
}


